package accs.model.ebay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.search.FromTerm;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import accs.model.AccountChecker;
import accs.model.Context;
import accs.model.ExtendedHttpClient;
import accs.model.mail.MailBoxListener;
import accs.model.mail.MailChecker;
import accs.model.utils.HeaderUtils;
import accs.model.utils.HtmlFormInputCollector;

public class EbayChecker implements AccountChecker {

	private static final Pattern WATCHING_PATTERN=Pattern.compile("Watching</a> \\(([0-9]*)\\)");
	private static final Pattern ACTIVE_PATTERN=Pattern.compile("Aktiv \\(([0-9]*)\\)<b></b>");
	private static final Pattern FINISHED_PATTERN=Pattern.compile("Beendet \\(([0-9]*)\\)<b></b>");
	private static final Pattern ALL_PATTERN=Pattern.compile("<b>Alle \\(([0-9]*)\\)</b>");
	private static final Pattern POSITIVE_PATTERN=Pattern.compile("Positive Bewertungen: \\s* ([0-9]*)<img");
	private static final Pattern NEGATIVE_PATTERN=Pattern.compile("Negative Bewertungen: \\s* ([0-9]*)</span>");
	private static final Pattern MEMBER_PATTERN=Pattern.compile("ds2arial13color3\">([0-9]+\\.[0-9]+\\.[0-9]+\\s*[a-z]+\\s*[A-Z]+[a-z]*)</span>");
	private static final Pattern SELLLIMIT_PATTERN=Pattern.compile("<div class=\"lstNum\">([0-9]+)</div>");
	private static final Pattern MONEYLIMIT_PATTERN=Pattern.compile("<div class=\"lstNum\">([A-Z]+\\s*[0-9.,]*)</div>");
	private static final Pattern LASTFEEDBACK_PATTERN=Pattern.compile("<td nowrap=\"nowrap\">([0-9]+\\.[0-9]+\\.[0-9]+ [0-9]+\\:[0-9]+)</td>");
	private static final Pattern POSITIVE_LIST_PATTERN=Pattern.compile("positive_[0-9]*\">([0-9]*)</a>");
	private static final Pattern NEUTRAL_NEGATIVE_LIST_PATTERN=Pattern.compile("fbsNeutralYukon\">([0-9]+)</span>");
	
	public EbayAccount mobileLogin(String user, String password, Context ctx) throws Exception {
		
		DefaultHttpClient httpclient=new ExtendedHttpClient(ctx);
		
		List<NameValuePair> list=new ArrayList<NameValuePair>();
//		for(NameValuePair bla : list) {
//			System.out.println(bla.getName()+" -> "+bla.getValue());
//		}
		
		HttpPost post=new HttpPost("https://m.ebay.com/Login.aspx?emvcc=0&nbcol=0%7Cnull");
		post.setHeader(HeaderUtils.getUserAgent());
		post.setHeader(HeaderUtils.getReferer("https://m.ebay.com/Login.aspx"));
				
		
		list.add(new BasicNameValuePair("emvcc","0"));
		list.add(new BasicNameValuePair("nbActionFormEncoding", "UTF-8"));
		list.add(new BasicNameValuePair("uex","True"));
		list.add(new BasicNameValuePair("btnSubmit","Sign in"));
		list.add(new BasicNameValuePair("uid",user));
		list.add(new BasicNameValuePair("upw",password));
		post.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
		
		HttpResponse resp2=httpclient.execute(post);
//		String location=resp2.getFirstHeader("Location").getValue();
		EntityUtils.consume(resp2.getEntity());
//		System.out.println(EntityUtils.toString(resp2.getEntity()));
//     	System.out.println("---------------------------------------------------------------");
		
		HttpGet get2=new HttpGet("https://m.ebay.com/Default.aspx");
		get2.setHeader(HeaderUtils.getUserAgent());
		get2.setHeader(HeaderUtils.getReferer("https://m.ebay.com/Login.aspx"));
		HttpResponse resp3=httpclient.execute(get2);
//		EntityUtils.consume(resp3.getEntity());
//		System.out.println(EntityUtils.toString(resp3.getEntity()));
		
		boolean valid = true;
		
		BufferedReader br=new BufferedReader(new InputStreamReader(resp3.getEntity().getContent(),"utf-8"));
		String line=null;
	
		String paymentMethod = "N/A";
		int pay = -6;
		int linenumber = 0;
		
		int watching=0;
		
		while((line=br.readLine())!=null) {
			line=line.trim(); //System.out.println(line);
			linenumber++;
			
			if(line.contains("Welcome!")){
//				System.out.println(line);
				valid = false;
			}
			
			//watching:
			{
				Matcher m=WATCHING_PATTERN.matcher(line);
				m.find();
				watching=Integer.parseInt(m.group(1));
				System.out.println("WATCHING: "+watching);
			}
			
			if(line.startsWith("<div class=\"box01\">")){
//				System.out.println(line);
				pay = linenumber+3;
			}
			if(linenumber == pay){
				paymentMethod = line.replace("<strong>", "").replace("</strong>", "");
			}
			
		}
		
		
		if(valid){
			return new EbayAccount(user, password, "", "", "", "", "", "");
		}else{
			return null;
		}
	}


	@Override
	public EbayAccount login(String user, String password, Context ctx) throws Exception {
		boolean valid = true;
		
		DefaultHttpClient httpclient=new ExtendedHttpClient(ctx);
		
		HttpGet get=new HttpGet("https://signin.ebay.de/ws/eBayISAPI.dll?co_partnerId=2&siteid=77&UsingSSL=1");
		get.setHeader(HeaderUtils.getUserAgent());
		HttpResponse resp=httpclient.execute(get);
		
		List<String> whitelist=new ArrayList<String>(Arrays.asList(new String[]{"MfcISAPICommand","UsingSSL","bUrlPrfx","bhid","co_partnerId","hmid","htmid","i1","inputversion","kdata","keepMeSignInOption","kgct","siteid","ru","rtmData","rqid","rhr	f","pp","pageType","pa3","pa2","pa1","omid","mid","lsv","lse","kgver","kgupg","kgstate"}));
		List<NameValuePair> list=HtmlFormInputCollector.collectInputs(new InputStreamReader(resp.getEntity().getContent(),"utf-8"),whitelist);
//		for(NameValuePair bla : list) {
//			System.out.println(bla.getName()+" -> "+bla.getValue());
//		}
		
		HttpPost post=new HttpPost("https://signin.ebay.de/ws/eBayISAPI.dll?co_partnerId=2&siteid=77&UsingSSL=1");
		post.setHeader(HeaderUtils.getUserAgent());
		post.setHeader(HeaderUtils.getReferer("https://www.ebay.de"));
		
		list.add(new BasicNameValuePair("userid",user));
		list.add(new BasicNameValuePair("pass",password));
		post.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
		
		HttpResponse resp2=httpclient.execute(post);
//		String location=resp2.getFirstHeader("Location").getValue();
		EntityUtils.consume(resp2.getEntity());
//		System.out.println(EntityUtils.toString(resp2.getEntity()));
//     	System.out.println("---------------------------------------------------------------");
		
		DefaultHttpClient httpclient2=new ExtendedHttpClient(ctx);
		httpclient2.setCookieStore(httpclient.getCookieStore());
		

		
		String selllimit = "";
		String moneylimit = "";
		int pay = -6;
		int all = 0;
		int allpos=0;
		int allneg=0;
		int active=0;
		int finished=0;
		int linenumber = 0;
		String membersince = "";
		String lastfeedback = "";
		String positiveList="", neutralList="", negativeList="";
		
		
		try {
		HttpGet get2=new HttpGet("http://my.ebay.de/ws/eBayISAPI.dll?MyEbayBeta&CurrentPage=MyeBayNextWatching");
		get2.setHeader(HeaderUtils.getUserAgent());
		get2.setHeader(HeaderUtils.getReferer("https://signin.ebay.de/ws/eBayISAPI.dll?co_partnerId=2&siteid=77&UsingSSL=1"));
		HttpResponse resp3=httpclient2.execute(get2);
//		EntityUtils.consume(resp3.getEntity());
//		System.out.println(EntityUtils.toString(resp3.getEntity()));
		
		
		BufferedReader br=new BufferedReader(new InputStreamReader(resp3.getEntity().getContent(),"utf-8"));
		String line=null;
		
		
		while((line=br.readLine())!=null) {
			line=line.trim();
//			System.out.println(line);
			linenumber++;
			
			if(line.contains("Passwort ist falsch")){
//				System.out.println(line);
				valid = false;
			}
			
			
			if(line.contains("Alle") && line.contains("Aktiv") && line.contains("Beendet")){
				Matcher m=ALL_PATTERN.matcher(line);
				m.find();
				all=Integer.parseInt(m.group(1));
				System.out.println("All: "+all);
				m=ACTIVE_PATTERN.matcher(line);
				m.find();
				active=Integer.parseInt(m.group(1));
				System.out.println("Active: "+active);
				m=FINISHED_PATTERN.matcher(line);
				m.find();
				finished=Integer.parseInt(m.group(1));
				System.out.println("Beendet: "+finished);
			}
			
		}
		
		DefaultHttpClient httpclient3=new ExtendedHttpClient(ctx);
		httpclient3.setCookieStore(httpclient2.getCookieStore());
		
		HttpGet get3=new HttpGet("http://feedback.ebay.de/ws/eBayISAPI.dll?ViewFeedback2&userid="+user+"&ftab=AllFeedback&rt=nc&myworld=true");
		get3.setHeader(HeaderUtils.getUserAgent());
		get3.setHeader(HeaderUtils.getReferer("http://my.ebay.de/ws/eBayISAPI.dll?MyEbayBeta&CurrentPage=MyeBayNextWatching"));
		HttpResponse resp4=httpclient3.execute(get3);
//		EntityUtils.consume(resp4.getEntity());
//		System.out.println(EntityUtils.toString(resp4.getEntity()));
		
		
		BufferedReader br2=new BufferedReader(new InputStreamReader(resp4.getEntity().getContent(),"utf-8"));
		line=null;
		
		while((line=br2.readLine())!=null) {
			line=line.trim();
//			System.out.println(line);
			linenumber++;
			
			if(line.contains("<span>Positive Bewertungen") && line.contains("Negative Bewertungen")){
//				System.out.println(line);
				Matcher m=POSITIVE_PATTERN.matcher(line);
				m.find();
				allpos=Integer.parseInt(m.group(1));
				System.out.println("Positiv: "+allpos);
				m=NEGATIVE_PATTERN.matcher(line);
				m.find();
				allneg=Integer.parseInt(m.group(1));
				System.out.println("Negativ: "+allneg);
				m=MEMBER_PATTERN.matcher(line);
				m.find();
				membersince=m.group(1);
				System.out.println(membersince);
				
				m=POSITIVE_LIST_PATTERN.matcher(line);
				while(m.find()) {
					positiveList+=m.group(1)+" ";
				}
				System.out.println("Positiv-Liste: "+positiveList);
				
				m=NEUTRAL_NEGATIVE_LIST_PATTERN.matcher(line);
				for(int i=0; m.find() & i<6; i++) {
					if(i<3) {
						neutralList+=m.group(1)+" ";
					} else {
						negativeList+=m.group(1)+" ";
					}
				}
				
				System.out.println("Neutral-Liste: "+neutralList);
				System.out.println("Negativ-Liste: "+negativeList);
			}
			
			if(line.contains("<td nowrap=\"nowrap\">")){
				Matcher m=LASTFEEDBACK_PATTERN.matcher(line);
				m.find();
				lastfeedback=m.group(1);
				System.out.println(lastfeedback);
			}
			
		}
		
		DefaultHttpClient httpclient4=new ExtendedHttpClient(ctx);
		httpclient4.setCookieStore(httpclient3.getCookieStore());
		
		HttpGet get4=new HttpGet("http://my.ebay.de/ws/eBayISAPI.dll?MyEbayBeta&CurrentPage=MyeBayNextAllSelling");
		get4.setHeader(HeaderUtils.getUserAgent());
		get4.setHeader(HeaderUtils.getReferer("http://feedback.ebay.de/ws/eBayISAPI.dll?ViewFeedback2&userid="+user+"&ftab=AllFeedback&rt=nc&myworld=true"));
		HttpResponse resp5=httpclient4.execute(get4);
//		EntityUtils.consume(resp5.getEntity());
//		System.out.println(EntityUtils.toString(resp5.getEntity()));
		
		
		BufferedReader br3=new BufferedReader(new InputStreamReader(resp5.getEntity().getContent(),"utf-8"));
		line=null;
		
		while((line=br3.readLine())!=null) {
			line=line.trim();
//			System.out.println(line);
			linenumber++;

			if(line.contains("<div class=\"lstNum\">")){
//				System.out.println(line);
				Matcher m=SELLLIMIT_PATTERN.matcher(line);
				m.find();
				selllimit=m.group(1);
				System.out.println("Verkaufslimit: "+selllimit);
				m=MONEYLIMIT_PATTERN.matcher(line);
				m.find();
				moneylimit=m.group(1);
				System.out.println("Betraglimit: "+moneylimit);
			}
		}
		
		} catch (Exception e) {
			e.printStackTrace();
			valid=false;
		}
		
		
//		http://feedback.ebay.de/ws/eBayISAPI.dll?ViewFeedback2&userid=suggaschabe&ftab=AllFeedback
//		der soll bewertung als käufer 
//		UND bewertung als Verkäufer checken 
//		Bewertung Käufer : 20,01,2012
//		Bewertung Verkäufer: 05,05,2010
		
		if(valid){
//			| USERNAME | PASSWORD | POSITIV(X X X) NEUTRAL(X X X) NEGATIV(X X X)  | MITGLIEDSEIT(DATUM LAND) | LETZTEBEWERTUNG(DATUM UHRZEIT) | VERKAUFSLIMIT(ARTIKEL BETRAG) | BEWERTUNG(POSITIV NEGATIV) | BEOBACHTUNGSLISTE(ALLE AKTIV BEENDET) |
			return new EbayAccount(user, password, positiveList+neutralList+negativeList, membersince, lastfeedback, selllimit+moneylimit, allpos+" "+allneg, String.valueOf(all+" "+active+" "+finished));
		}else{
			return null;
		}
		
	}
	
	public static String UserIdRecognizer(String user, String pass) throws ClientProtocolException, IOException{
		
//		https://scgi.ebay.de/ws/eBayISAPI.dll?UserIdRecognizer
		
		DefaultHttpClient httpclient=new DefaultHttpClient();
		
		HttpGet get=new HttpGet("https://scgi.ebay.de/ws/eBayISAPI.dll?UserIdRecognizerShow");
		get.setHeader(HeaderUtils.getUserAgent());
		HttpResponse resp=httpclient.execute(get);
		
		List<String> whitelist=new ArrayList<String>(Arrays.asList(new String[]{}));
		List<NameValuePair> list=HtmlFormInputCollector.collectInputs(new InputStreamReader(resp.getEntity().getContent(),"utf-8"),whitelist);
//		for(NameValuePair bla : list) {
//			System.out.println(bla.getName()+" -> "+bla.getValue());
//		}
		
		HttpPost post=new HttpPost("https://scgi.ebay.de/ws/eBayISAPI.dll?UserIdRecognizer");
		post.setHeader(HeaderUtils.getUserAgent());
		post.setHeader(HeaderUtils.getReferer("https://scgi.ebay.de/ws/eBayISAPI.dll?UserIdRecognizerShow"));
		
		list.add(new BasicNameValuePair("useremail",user));
		list.add(new BasicNameValuePair("ConfirmUserEmail",user));
		list.add(new BasicNameValuePair("MfcISAPICommand","UserIdRecognizer"));
		post.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
		
		HttpResponse resp2=httpclient.execute(post);
//		String location=resp2.getFirstHeader("Location").getValue();
		EntityUtils.consume(resp2.getEntity());
//		System.out.println(EntityUtils.toString(resp2.getEntity()));
//     	System.out.println("---------------------------------------------------------------");
		
//		HIER DER CODE UM DEN USERNAMEN AUS DER MAIL ZU LESEN
		String secuser = "";
		MailChecker checker=new MailChecker();
		checker.checkAdress(user, pass, new MailBoxListener() {
			public void mailboxOpen(Store store) throws Exception { System.out.println("open");
				String res = "";
			    Folder folder=store.getFolder("INBOX");
				folder.open(Folder.READ_ONLY);
				
				for(Message msg:folder.search(new FromTerm(new InternetAddress("aw-confirm@ebay.com")))) {System.out.println("message");
					try {
						
						BufferedReader reader=new BufferedReader(new InputStreamReader(msg.getInputStream(),"iso-8859-1"));
						String line=null;
						
						while((line=reader.readLine())!=null) {
							if(line.contains("Ihr Mitgliedsname ist:")){
								System.out.println(line);
								res = line.replace(" Ihre registrierte=", "").replace("Ihr Mitgliedsname ist:", "").replace(" ","");
							}
						}
					} catch(Exception e) {
						e.printStackTrace();
					}
				}
				
				folder.close(false);
			}
		});
		
		return secuser;
	}


	@Override
	public URL getImage() {
		return EbayChecker.class.getResource("/accs/gui/img/ebay.png");
	}


	@Override
	public String getName() {
		return "ebay";
	}
}
